<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class SearchController extends App_Zend_Controller_Action_Shop
{
	public function detailAction()
	{
		$this->view->styleName = 'product-list';
		$keyword=$this->_request->getParam('keyword');
		if($keyword == ''){
			$this->_forward('index','error');
			return false;
		}
		
		$page = $this->_request->getParam('page',1);
		$order = $this->_request->getParam('order',0);
		
		$this->getHelper('Fenlei')->getCategories();
		
		//L　SEARCH
		$myCache=Zend_Registry::get('myCache');
		$cacheId=md5($keyword);
		$result=$myCache->load($cacheId);
		if(!$result){
			Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive());
			$index=Zend_Search_Lucene::open(MY_ROOT."/indexdata/index");
			Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
			$query=Zend_Search_Lucene_Search_QueryParser::parse($keyword,'utf-8');
			$hits=$index->find($query,'px', SORT_ASC);
			$hits=$index->find($query);
			$myHits=array();
			foreach($hits as $hit){
				$newHits=new stdClass();
				$newHits->PID=$hit->PID;
				$myHits[]=$newHits;
				unset($newHits);
			}
			$myCache->save($myHits,$cacheId);
		}else{
			$hits=$result;
		}
		$this->view->isNoSearch = false;
		if(count($hits) == 0){
			$this->view->isNoSearch = true;
			$index=Zend_Search_Lucene::open(MY_ROOT."/indexdata/index");
			Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_OR);
			$query=Zend_Search_Lucene_Search_QueryParser::parse($keyword,'utf-8');
			$hits=$index->find($query,'px', SORT_ASC);
			$hits=$index->find($query);
			$myHits=array();
			$hitIndex = 0;
			foreach($hits as $hit){
				$newHits=new stdClass();
				$newHits->PID=$hit->PID;
				$myHits[]=$newHits;
				unset($newHits);
			}
		}
		
		$PIDS = array();
		foreach ($hits as $hit)
		{
			$PIDS[] = $hit->PID;
		}
		
		/**refine search **/
		$productAttributeMapSearch = array();
		$attr = new CAttr();
		$f = $this->getRequest()->getParam('f', '');
        if ($f) {
            $f = base64_decode($f);     
            		
            $filterStr = explode(',', $f);
            $filter = array();
            foreach ($filterStr as $v) {
            	$row = '';
            	$row = $attr->find($v)->current();
            	if ($row->type == '1') {
            		$filter['category'] = $v;
            	} elseif ($row->type == '2') {
            		$filter['brand'] = $v;
            	} elseif ($row->type == '3') {
            		$filter['player'] = $v;
            	} else {
            		exit();
            	}
            }
        } else {
            $filter = array();
        }
        
        $tmpPids = array();
        $tmpPids = $PIDS;
        foreach ($filter as $v) {
        	$tmpPids = $attr->filterItemIdByAttr($tmpPids, $v);
        	if (!$tmpPids) {
				break;
			}
        }
		$PIDS = $tmpPids;
		
		$productAttributeMapSearch = array();
		$filterType = array_keys($filter);
				
		if (!in_array('category', $filterType)) {	
			$categoryAttr = $attr->getByType(1);		
			foreach ($categoryAttr as $v) {						
				$tmp = $filter;
				$tmp['category'] = $v->attr_id;	
				$tmpItemArr = array();		
				$tmpItemArr = $PIDS;	
				foreach ($tmp as $_v) {
					$tmpItemArr = $attr->filterItemIdByAttr($tmpItemArr, $_v);
					if (!$tmpItemArr) {
						break;
					}
				}
				if ($tmpItemArr) {
					$productAttributeMapSearch['Category'][] = $v;
				}
			}
		}
		if (!in_array('brand', $filterType)) {
        	$brandAttr = $attr->getByType(2);
			foreach ($brandAttr as $v) {
				$tmp = $filter;
				$tmp['brand'] = $v->attr_id;	
				$tmpItemArr = array();		
				$tmpItemArr = $PIDS;	
				foreach ($tmp as $_v) {
					$tmpItemArr = $attr->filterItemIdByAttr($tmpItemArr, $_v);
					if (!$tmpItemArr) {
						break;
					}
				}
				if ($tmpItemArr) {
					$productAttributeMapSearch['Brand'][] = $v;
				}
			}
		}
		if (!in_array('player', $filterType)) {
        	$playerAttr = $attr->getByType(3);
			foreach ($playerAttr as $v) {
				$tmp = $filter;
				$tmp['brand'] = $v->attr_id;	
				$tmpItemArr = array();		
				$tmpItemArr = $PIDS;	
				foreach ($tmp as $_v) {
					$tmpItemArr = $attr->filterItemIdByAttr($tmpItemArr, $_v);
					if (!$tmpItemArr) {
						break;
					}
				}
				if ($tmpItemArr) {
					$productAttributeMapSearch['Player'][] = $v;
				}
			}
		}
	
		$this->view->productAttributeMapSearch = $productAttributeMapSearch;
		foreach ($filter as $v) {
			$selectedProductAttributesSearch[] = $attr->find($v)->current();
		}
        $this->view->selectedProductAttributesSearch = $selectedProductAttributesSearch;
        $this->view->refineSearch = 1;
        $this->view->filterIds = array_values($filter);
		/**refine search **/
		
		
		
		//L　SEARCH
		if(!empty($PIDS))
		{
			$itemCounts = count($PIDS);
		} else {
			$itemCounts = 0;
		}
		
		if($this->view->isNoSearch && count($hits)>=10){
			$itemCounts = 10;
		}
		
		Zend_Loader::loadClass("CFilter");
    	$pageArray = CFilter::filterPage ($page, $itemCounts, 24);

		$itemArray = array();
		$myCache = Zend_Registry::get('myCache');
		$itemMap = CCache::getCombinlistItemMap();
		$offset = ($page-1)*24;
		for($i=$offset;$i<$offset+24;$i++){
			if($i<$itemCounts){
				array_push($itemArray,$itemMap[$PIDS[$i]]);
			}
		}

		Zend_Loader::loadClass("CPage");
    	$pageString = CPage::divPages( $pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH."/search-detail/?keyword=".rawurlencode($keyword)."&order=$order&f=" . base64_encode($f)); 		
		$this->view->assign ( "pageString", $pageString );
    	$this->view->assign ( "pageArray", $pageArray );
		$this->view->assign('itemArray',$itemArray);
		$this->view->assign('itemCounts',$itemCounts);
		$this->view->assign('order',$order);
		$this->view->assign('page',$page);
		$this->view->assign('keyword',$keyword);
		$this->view->webSiteTitle = $keyword.', Search Results for '.$keyword.', Page '.$page;
		$this->view->webSiteKeywords = $keyword;
		$this->view->webSiteDescription = $keyword. ', Your Search Results for '.$keyword.', Page '.$page;
		
		//SET META FOR FACEBOOK
        $this->getHelper ('layout')->getView()->headMeta()->setName('og:title', $keyword);
		$this->getHelper ('layout')->getView()->headMeta()->setName('og:type', 'jersery');
		$this->getHelper ('layout')->getView()->headMeta()->setName('og:url', MY_URL);
		$this->getHelper ('layout')->getView()->headMeta()->setName('og:image', MY_URL.'/images/logo.jpg');
		$this->getHelper ('layout')->getView()->headMeta()->setName('og:site_name', 'newjerseysoccer.net');
		$this->getHelper ('layout')->getView()->headMeta()->setName('og:description', $keyword);
	}

	
	public function postAction(){
	
		//$this->_helper->viewRenderer->setNoRender();
		
		//$this->getHelper ('layout')->disableLayout ();
	
	}
    
	public function testAction()
	{
		$this->getHelper('layout')->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
		
		ignore_user_abort();
		set_time_limit(0);
		
		
		$sql = 'select * from zcshop_keywords';
		
		$member = new CMember();
		$db = $member->getAdapter();
		
		$result = $db->fetchAll($sql);
		$index=Zend_Search_Lucene::open(MY_ROOT."/indexdata/index");
		Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
		
		foreach ($result as $v) {			
			$query=Zend_Search_Lucene_Search_QueryParser::parse($v['keywords'],'utf-8');
			$hits=$index->find($query);
			$myHits=array();
			if (!empty($hits)) {
				$counts = count($hits);
				$sql = 'update zcshop_keywords set product_num=' . $counts . ' where keywords_id=' . $v['keywords_id'];
				$db->query($sql);
				foreach($hits as $hit){					
					$sql = 'insert into zcshop_product_keywords_related(productid, keywords_id) values(' . $hit->PID . ', ' . $v['keywords_id'] . ')';
					$db->query($sql);
				}
			}			
		}		
	}
    
}
